package com.hgc.ch02.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created by 01367627 on 2019/7/8.
 */
public class FutureAndCallable {

    private static class MyCallable implements Callable<Integer>{

        private int sum;

        public MyCallable(int sum) {
            this.sum = sum;
        }

        @Override
        public Integer call() throws Exception {
            System.out.println("Callable开始计算=======================");
            for(int i=0;i<50000;i++){
                sum += i;
            }
            Thread.sleep(2000);
            System.out.println("Callable结束计算=======================");
            return sum;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int sum = 0;
        for(int i=0;i<50000;i++){
            sum += i;
        }
        System.out.println("直接计算：" + sum);
        MyCallable myCallable = new MyCallable(0);
        FutureTask<Integer> task = new FutureTask<Integer>(myCallable);
        new Thread(task).start();
        System.out.println("主线程执行中==============");
        System.out.println("future计算：" + task.get());
    }

}
